package controller;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import entity.HomeNews;
import entity.School;
import entity.User;
import net.sf.json.JSONObject;
import service.SchoolService;
import service.UserService;
import util.ResponseUtil;

@Controller
@RequestMapping("/user")
public class UserController {
	@Resource
	private UserService userService;
	@Resource
	private SchoolService schoolService;
	
	//http://localhost:8080/CampusApp/user/adduser.do?username=恒&password=heng&schoolName=青岛海洋
		@RequestMapping("/adduser")
		public void addUser(HttpServletRequest request, HttpServletResponse response) throws Exception {
			 String username = request.getParameter("username");
			 String password = request.getParameter("password");
			 String schoolName=request.getParameter("schoolName");
			User dbuser = userService.findByUserName(username);
			if(dbuser!=null){
				JSONObject result = getResultFrom(false, "该用户名已经存在", null);
				ResponseUtil.write(response, result);
				return;
			}
			User user = new User();
			user.setUserName(username);
			user.setPassword(password);
			List<School> schools=schoolService.getAllSchoolInfo();
			//user.set
			boolean schoolFlag=false;
			for(int i=0;i<schools.size();i++){
				String schoolName2 = schools.get(i).getSchoolName();
				if(schoolName2.equals(schoolName)){
					user.setSchooleId(i+1);
					schoolFlag=true;
					break;
				}
			}
			if(!schoolFlag){
				int count=schoolService.addNewSchool(schoolName);
				if(count>=0){
					School school=schoolService.getSchoolBySchoolName(schoolName);
					user.setSchooleId(school.getSchoolId());
				}else{
					
				}
			}
			int count=0;
			count = userService.addUser(user);
			if (count > 0) {
				User newUser=userService.findByUserName(user.getUserName());
				JSONObject result = getResultFrom(true, "用户注册成功", newUser);
				ResponseUtil.write(response, result);
			} else {
				JSONObject result = getResultFrom(false, "用户注册失败", null);
				ResponseUtil.write(response, result);
			}
		}
		public JSONObject getResultFrom(boolean successful,String message,Object data){
			JSONObject result = new JSONObject();
			result.put("successful",successful);
			result.put("message", message);
			result.put("data", data);
			return result;
		}
		//http://localhost:8080/CampusApp/user/loginuser.do?username=123&password=123
		@RequestMapping("/loginuser")
		public void loginUser(HttpServletRequest request, HttpServletResponse response) throws Exception {
			 String username = request.getParameter("username");
			 String password = request.getParameter("password");
			User dbUser=null;
			boolean flag=false;
			dbUser=userService.findByUserName(username);
			if(dbUser!=null&&password!=null){
				String pwd = dbUser.getPassword();
				if(password.equals(pwd)){
					flag=true;
				}
			}
			if (flag) {
				JSONObject result = getResultFrom(true, "用户登陆成功", dbUser);
				ResponseUtil.write(response, result);
			} else {
				JSONObject result = getResultFrom(false, "用户登陆失败", null);
				ResponseUtil.write(response, result);
			}
		}
		@RequestMapping("/updateuser")
		public void updateUser(HttpServletRequest request, HttpServletResponse response) throws Exception {
			String username = request.getParameter("username");
			String password = request.getParameter("password");
//			String username = "admin";
//			String password = "admin123";
			User user=new User();
			user.setUserName(username);
			user.setPassword(password);
			int count=0;
			count=userService.update(user);
			if (count>0) {
				JSONObject result = getResultFrom(true, "用户信息修改成功", user);
				ResponseUtil.write(response, result);
			} else {
				JSONObject result = getResultFrom(false, "用户信息修改失败", null);
				ResponseUtil.write(response, result);
			}
		}
	
	
	
	
	
	
	
	
	@RequestMapping("/login")
	public String login(User user, HttpServletRequest request, HttpServletResponse response) throws Exception {
		int flag = 0;
		Subject subject = SecurityUtils.getSubject();
		UsernamePasswordToken token = new UsernamePasswordToken(user.getUserName(), user.getPassword());
		try {
			subject.login(token);
			Session session = subject.getSession();
			System.out.println("sessionId:" + session.getId());
			System.out.println("sessionHost:" + session.getHost());
			System.out.println("sessionTimeout:" + session.getTimeout());
			session.setAttribute("info", "session鏁版嵁");
			flag = 1;
		} catch (Exception e) {
			e.printStackTrace();
			flag = 0;
			request.setAttribute("user", user);
			request.setAttribute("errorMsg", "鐢ㄦ埛鍚嶆垨瀵嗙爜閿欒");
		}
		JSONObject result = new JSONObject();
		if (flag > 0) {
			result.put("result", true);
		} else {
			result.put("result", false);
		}
		ResponseUtil.write(response, result);

		return null;

	}
	//http://localhost:8080/CampusApp/user/gettestdata.do
	//http://192.168.16.140:8080/CampusApp/user/gettestdata.do
	@RequestMapping("/gettestdata")
	public void getTestData(HttpServletRequest request, HttpServletResponse response) throws Exception {
		System.out.println("sdfddddddddddddddddddddddd");
		String str = "testdata";
		User user = new User();
		user.setUserName(str);
		user.setPassword("123");
		JSONObject result = JSONObject.fromObject(user);
		ResponseUtil.write(response, result);
	}

	@RequestMapping("/getHomeNewData")
	public void getHomeNewData(HttpServletRequest request, HttpServletResponse response) throws Exception {
		List<HomeNews> newslist = new ArrayList<>();
		setDataToList(newslist);
		JSONObject result = new JSONObject();
		result.put("result", newslist);
		ResponseUtil.write(response, result);

	}

	private void setDataToList(List<HomeNews> newslist) {
		// TODO Auto-generated method stub
		String[] imgs = {
				"http://a3.qpic.cn/psb?/V10hoDo70KQ2zB/ZsQyZOhje7Js4ND7L68MNa3hWD3Oj2W1sBX8Qj1aCGM!/b/dG0BAAAAAAAA&bo=KgLRAQAAAAARB8g!&rf=viewer_4",
				"http://a3.qpic.cn/psb?/V10hoDo70KQ2zB/bVYWNt1LYM85E8zWkj6GILMapN3vmvIzYB9BjaX5qjc!/b/dG0BAAAAAAAA&bo=vALSAQAAAAARAFo!&rf=viewer_4",
				"http://a3.qpic.cn/psb?/V10hoDo70KQ2zB/mEHjOpvvWd3AQOc9exxjNAtKKcSVNY3WhOXgNU8tsuE!/b/dG0BAAAAAAAA&bo=vALRAQAAAAARAFk!&rf=viewer_4",
				"http://a2.qpic.cn/psb?/V10hoDo70KQ2zB/BF2akHshKyERCi2LsCNtEZWO.4xWC7KeiWC4ElQrvpY!/b/dGwBAAAAAAAA&bo=vALRAQAAAAARAFk!&rf=viewer_4",
				"http://a1.qpic.cn/psb?/V10hoDo70KQ2zB/7B2O*Frel9126FavOgc754*m48XRfBFfveaCDM2qkEc!/b/dG4BAAAAAAAA&bo=VQLSAQAAAAARALM!&rf=viewer_4"

		};
		String[] webs = { "http://www.ytu.edu.cn:80/xxyw/2601.jhtml", "http://www.ytu.edu.cn:80/xxyw/2443.jhtml",
				"http://www.ytu.edu.cn:80/xxyw/2394.jhtml", "http://www.ytu.edu.cn:80/xxyw/2375.jhtml",
				"http://www.ytu.edu.cn:80/xxyw/2555.jhtml"

		};
		String[] titels = { "灞变笢鐪佸甯稿缁勭粐閮ㄩ儴闀挎潹涓滃鏉ユ牎璋冪爺", "瀛︽牎鍙紑鍏氶寤夋斂寤鸿宸ヤ綔浼氳", "鐑熷彴澶у2017骞村伐浣滅爺璁ㄤ細鍙紑", "鐑熷彴澶у鐞嗕簨浼氭垚绔�",
				"鍏氬涔﹁宕旀槑寰疯皟鐮斺�滅涓�涔﹁鈥濆拰鎸傝亴骞查儴宸ヤ綔"

		};
		for (int i = 0; i < titels.length; i++) {
			HomeNews homeNews = new HomeNews();
			homeNews.setTitle(titels[i]);
			homeNews.setImgUrl(imgs[i]);
			homeNews.setWebUrl(webs[i]);
			newslist.add(homeNews);
		}
	}
	
}
